<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Home\Controller;

use Think\Controller;

class PublicController extends Controller {

     /**
     * 生成获取验证码
     * @param type $phone 手机号
     * @param type $type  获取验证码类型 1：注册时获取 2：重置密码时获取
     */
    public function reg_code() {
        if (IS_POST || IS_GET) {
            $phone = I("mobile");
            $data = array(
                'val' => RF,
                'str' => '失败！'
            );
            if (empty($phone)) {
                $data['str'] .= '请输入手机号！';
            } elseif (!is_numeric($phone)) {
                $data['str'] .= '您的输入不规范！';
            } elseif (strlen($phone) != 11) {
                $data['str'] .= '请输入的手机号位数不正确！';
            } else {
                
                $code = rand(100000, 999999); //生成随机6位注册码
                $sql = M('code');
                $tpl = 'regist';
                $d['type'] = 3;

                $d['mobile'] = $phone;
                $d['code'] = $code;
                $d['time'] = $time = time();

                $w['mobile'] = $phone;
                $w['time'] = array('GT', time() - 5 * 60);
                $check = $sql->where($w)->count('cid'); //防止同一用户多次获取验证码
                if ($check) {
                    $data['val'] = RF;
                    $data['str'] = '获取验证码过于频繁！';
                } else {
                    $a = $sql->add($d);
                    if (!empty($a)) {
                        if (sendSmsByTpl($tpl, $phone, $code)) {
                            $data['val'] = RS;
                            $data['str'] = '获取验证码成功！';
                        } else {
                            $data['str'] = '获取验证码失败！';
                        }
                    }
                }
            }
        }
        $this->ajaxReturn($data);
    }
    
    	private function checkSignature()
	{
		$signature = $_GET["signature"];
		$timestamp = $_GET["timestamp"];
		$nonce = $_GET["nonce"];	

		$token = "wodehaisishenwukeji";
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );

		if( $tmpStr == $signature ){
		return true;
		}else{
		return false;
		}
	}
	/**
         * 微信token验证 微信公众平台基本设置
         */
	public function valid()
	 {
	  $echoStr = $_GET["echostr"];
	  //valid signature , option
	  if($this->checkSignature()){
	  echo $echoStr;
	  exit;
	  }
	 }
}
